package com.example.demo.service.impl;

import com.example.demo.bean.Regional;
import com.example.demo.common.ServerResponse;
import com.example.demo.dao.RegionalRepository;
import com.example.demo.service.RegionalService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/6/23
 */
@Service
@AllArgsConstructor
public class RegionalServiceImpl implements RegionalService {
    private final RegionalRepository regionalRepository;

    @Override
    public ServerResponse<List<Regional>> list(Integer parentId) {
        List<Regional> regionalList = regionalRepository.findByParentIdOrderById(parentId);
        if (regionalList.isEmpty()) {
            return ServerResponse.createByErrorMessage("该父节点为空");
        }
        return ServerResponse.createBySuccess(regionalList);
    }
    @Override
    public ServerResponse findOne(Integer id){
        Optional<Regional> regional = regionalRepository.findById(id);
        if (regional.isPresent()){
            return ServerResponse.createBySuccess(regional);
        }
       return ServerResponse.createByErrorMessage("该部门不存在");
    }

    public ServerResponse<Regional> addRegional(Regional regional){
        Regional regionalAdd = regionalRepository.save(regional);
        return ServerResponse.createBySuccessMessage("添加成功", regionalAdd);
    }

    @Override
    public void deleteRegional(Integer id) {
        regionalRepository.deleteById(id);

    }

    @Override
    public ServerResponse<Regional> regionalUpdate(Regional regional) {
        Regional updateRegional = new Regional();
        updateRegional.setId(regional.getId());
        updateRegional.setName(regional.getName());
        updateRegional.setParentId(regional.getParentId());
        regional=regionalRepository.save(updateRegional);
        return ServerResponse.createBySuccessMessage("更新成功", regional);
    }
}
